#region

using System;
using System.Linq;
using System.Threading;
using System.Web.Mvc;
using log4net;
using xConnected.Common.Country;
using xConnected.Core.Model;
using xConnected.Service;

#endregion

namespace xConnected.Controllers
{
    public class CountryController : BaseController<Country>
    {
        private readonly CountryService _countryService;
        private readonly LanguageService _languageService;

        public CountryController(CountryService countryService, LanguageService languageService)
        {
            _countryService = countryService;
            _languageService = languageService;
        }


        public JsonResult List(string search = "", int pageIndex = 0, int pageSize = 10)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var page = search != ""
                               ? _countryService.GetAllPagedSearched(search, pageIndex, pageSize)
                               : _countryService.GetAllPaged(pageIndex, pageSize);
                var countries = page.Entities.ToList().Select(e => new
                                                                       {
                                                                           e.Id,
                                                                           e.Created,
                                                                           e.Updated,
                                                                           Description =
                                                                       CountryRes.ResourceManager.GetString(e.Key,
                                                                                                            Thread.
                                                                                                                CurrentThread
                                                                                                                .
                                                                                                                CurrentCulture),
                                                                           e.ShortName,
                                                                           e.Key
                                                                       });

                return
                    Json(
                        new {search, page.Count, page.CurrentPage, page.PageSize, page.PagesCount, Entities = countries},
                        JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult Save(Country country)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                _countryService.SaveOrUpdate(country);
                return Json(country.Id, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        [HttpPost]
        public JsonResult DeleteCountry(int id)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var country = _countryService.GetById(id);
                _countryService.Delete(country);
                return Json("OK", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        public JsonResult GetCountriesAutocomplete(string searchTerm, int maxRows)
        {
            ILog log = LogManager.GetLogger(GetType());
            try
            {
                var languages = _languageService.GetAll();
                var countriesEn = _countryService.GetAll().Select(
                        c => new
                                 {
                                     c.Id,
                                     TitleTranslation = c.TitleTranslations.FirstOrDefault(
                                     tt => tt.LanguageId == languages.FirstOrDefault(l => l.ShortName == "en").Id).Text
                                     
                                 });
                var countriesDe = _countryService.GetAll().ToList().Select(
                        c => new
                                 {
                                     c.Id,
                                     TitleTranslation = c.TitleTranslations.FirstOrDefault(
                                     tt => tt.LanguageId == languages.FirstOrDefault(l => l.ShortName == "de").Id).Text
                                 });
                var countriesHr = _countryService.GetAll().Select(
                        c => new
                                 {
                                     c.Id,
                                     TitleTranslation = c.TitleTranslations.FirstOrDefault(
                                     tt => tt.LanguageId == languages.FirstOrDefault(l => l.ShortName == "hr").Id).Text
                                 });
                var countries = countriesEn.Union(countriesDe).Union(countriesHr);
                if (searchTerm != "")
                {
                    countries =
                        countries.Where(l => l.TitleTranslation.ToLower().Contains(searchTerm.ToLower())).Take(maxRows);
                }
                return Json(countries, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message + Environment.NewLine + "Stack: " + ex.StackTrace, ex);
                return Json(new {Result = "ERROR", ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }
    }
}